package com.chaopei.mapper.impl;

import com.chaopei.entity.Emp;
import com.chaopei.mapper.EmpMapper;
import com.chaopei.tools.DBTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Corday 天涯
 * @Date 2022/3/23 15:04
 */
public class EmpMapperImpl implements EmpMapper {
    @Override
    public List<Emp> selectAllEmps() {
        Connection connection = DBTools.getConn();
        // 生成数据库操作对象PreparedStatament,  Statament(已经不用啦)
        PreparedStatement ps = null;
        String sql = "select eno,ename,salary,dno from emp";
        List<Emp> list = new ArrayList<>();
        try {
            //拿到一个数据库操作对象
            ps = connection.prepareStatement(sql);
            //执行查询拿到一个结果集对象,保存查询到的所有记录
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {//eid,ename,salary,dno
                Integer eno = rs.getInt("eno");
                String ename = rs.getString("ename");
                Double salary = rs.getDouble("salary");
                Integer dno = rs.getInt("dno");
                Emp emp = new Emp(eno, ename, salary, dno);
                list.add(emp);
            }
//            关闭连接对象
            DBTools.closeConn(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public Emp selectEmpByEid(Integer eno) {
        Connection connection = DBTools.getConn();
        // 生成数据库操作对象PreparedStatament
        PreparedStatement ps = null;
        String sql = "select eno,ename,salary,dno from where eno=?";
        Emp emp=null;
        try {
          ps = connection.prepareStatement(sql);
          ps.setInt(1,eno);
          ResultSet rs = ps.executeQuery();
          if(rs!=null) {
              //拿到第一条记录
              rs.next();
              Integer enot = rs.getInt("eno");
              String ename = rs.getString("ename");
              Double salary = rs.getDouble("salary");
              Integer dno = rs.getInt("dno");
              emp = new Emp(enot, ename, salary, dno);
          }
          //关闭连接
          DBTools.closeConn(connection);
        } catch (SQLException e) {
            System.out.println("查询有问题!");
        }
        return emp;
    }

    @Override
    public Integer updateEmpByEid(Integer eno, Double salary) {
        Connection connection = DBTools.getConn();
        // 生成数据库操作对象PreparedStatament
        PreparedStatement ps = null;
        String sql = "update emp set salary=? where eno=?";
        Integer it=null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setDouble(1,salary);
            ps.setInt(2,eno);
            it=ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return it;
    }
}
